package cn.alex.sso.project.service.impl;

import cn.alex.sso.framework.core.PageHelper;
import cn.alex.sso.framework.global.ServiceException;
import cn.alex.sso.project.entity.SysRole;
import cn.alex.sso.project.mapper.SysRoleMapper;
import cn.alex.sso.project.mapper.SysUserRoleMapper;
import cn.alex.sso.project.service.SysRoleClientService;
import cn.alex.sso.project.service.SysRoleService;
import cn.alex.sso.project.sync.event.RoleAbstractDataSyncEvent;
import cn.alex.sso.project.sync.module.RoleDataSyncModule;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Alex
 * @description 针对表【sys_role(角色表)】的数据库操作Service实现
 * @createDate 2024-09-24 17:05:38
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    private final SysRoleClientService roleClientService;
    private final SysUserRoleMapper userRoleMapper;

    @Override
    public IPage<SysRole> getPage(SysRole entity) {
        return baseMapper.selectPage(PageHelper.getPage(), baseMapper.getQueryWrapper(entity));
    }

    @Override
    public void add(SysRole entity) {
        entity.setCreatedTime(new Date());
        entity.setUpdatedTime(new Date());
        baseMapper.insert(entity);

        SpringUtil.getApplicationContext().publishEvent(new RoleAbstractDataSyncEvent(this, entity, RoleDataSyncModule.Trigger.ADD));
    }

    @Override
    public void edit(SysRole entity) {
        entity.setUpdatedTime(new Date());
        baseMapper.updateById(entity);

        SpringUtil.getApplicationContext().publishEvent(new RoleAbstractDataSyncEvent(this, entity, RoleDataSyncModule.Trigger.EDIT));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        List<Long> userIdList = userRoleMapper.getUserIdListByRoleId(ids);
        if (CollUtil.isNotEmpty(userIdList)) {
            throw new ServiceException("该角色下存在用户，无法删除");
        }
        baseMapper.deleteByIds(ids);

        // 需要在删除应用和角色关联关系前同步数据
        SpringUtil.getApplicationContext().publishEvent(new RoleAbstractDataSyncEvent(this, ids, RoleDataSyncModule.Trigger.DELETE));

        ids.forEach(roleClientService::removeByRoleId);
    }
}




